package com.lowca.news.service.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

import com.lowca.news.entity.Role;
import com.lowca.news.entity.User;

public class UserDetailsAdapter implements UserDetails {

	private static final long serialVersionUID = 1L;

	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserDetailsAdapter(User user) {
		this.user = user;
	}

	@Override
	public String getPassword() {
		return this.getUser().getPassword();
	}

	@Override
	public String getUsername() {
		return this.getUser().getUsername();
	}

	public boolean isAccountNonExpired() {
		return !this.getUser().getExpired();
	}

	public boolean isAccountNonLocked() {
		return !this.getUser().getLocked();
	}

	public boolean isCredentialsNonExpired() {
		return !this.getUser().getCredentialsExpired();
	}

	public boolean isEnabled() {
		return this.getUser().getEnabled();
	}

	public Collection<GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
		Set<Role> roles = user.getRoles();
		for (Role role : roles) {
			list.add(new GrantedAuthorityImpl(role.getName()));
		}
		return list;
	}

	public UserDetailsAdapter() {
		super();
	}

}
